package com.lanswon.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.lanswon.common.constants.Constants;
import com.lanswon.common.util.StringUtil;
import com.lanswon.entity.UserVO;

@Service("loginService")
public class LoginService {
	
	@Autowired
	private UserService userService;

	public Map<String, Object> loginCheck(String username, String password, String code, HttpServletRequest request) {
		
		Map<String, Object> map = new HashMap<>();
		if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
			map.put("code", 2);
			map.put("msg", "用户名或密码不正确");
			return map;
		}
		try {
			password = StringUtil.md5(password);
			UsernamePasswordToken token = new UsernamePasswordToken(username,password);
			//token.setRememberMe(true);
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.login(token);
			if(currentUser.isAuthenticated()) {
				UserVO user = currentUser.getPrincipals().oneByType(UserVO.class);
				request.getSession().setAttribute(Constants.SESSION_KEY_ADMIN_LOGIN_NAME, user);
			}
			map.put("username", username);
			map.put("password", password);
			UserVO userVO = userService.findUserByCondition(map);
			request.getSession().setAttribute("user", userVO);
			
			map.put("code", 1);
			map.put("msg", "登陆成功");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			map.put("code", 2);
			map.put("msg", "用户名或密码不正确");
		}
		return map;
	}
	
	
	
}
